package com.zhida.jiyangcenter.order

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.view.MotionEvent
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.vehicle.inspection.api.toRequestBody
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.CommentGoodsShowEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.order.adapter.CommentAdapter
import com.zhida.jiyangcenter.order.adapter.PhotoInfo
import com.zhida.jiyangcenter.utils.FilterUtil
import com.zhida.jiyangcenter.utils.GlideEngine
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_comment_activity.*
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.util.ArrayList

@TitleBar(false)
@ContentLayout(R.layout.activity_comment_activity)
class CommentOrderActivity : BaseActivity() {
    val adapter = Adapter()
    private val mPhotoInfos = ArrayList<PhotoInfo>()
    private val MAX_NUM = 3
    private var mTempPhotoInfo: PhotoInfo? = null
    private var mPhotoIndex = 1
    private var mAdapter: CommentAdapter? = null
    private var ratingNum: Float = 5F
    private var serverNum: Float = 5F
    private var wuliuNum: Float = 5F

    @SuppressLint("ClickableViewAccessibility")
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("订单评价").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.operationText("发布"){
            comment()
        }.getOperationTextView().setTextColor(resColor(R.color.white))
        rating_product_bar.setOnRatingChangeListener { _, rating ->
            if (rating < 1) rating_product_bar.rating = 1f
            ratingNum = rating
        }
        rating_wuliu_bar.setOnRatingChangeListener { _, rating ->
            if (rating < 1) rating_wuliu_bar.rating = 1f
            wuliuNum = rating
        }
        rating_fuwu_bar.setOnRatingChangeListener { _, rating ->
            if (rating < 1) rating_fuwu_bar.rating = 1f
            serverNum = rating
        }
        radio_anonymity.setOnClickListener {
            radio_anonymity.setChecked(
                !radio_anonymity.isChecked,
                true
            )
        }
        ll_radio_anonymity.setOnClickListener {
            radio_anonymity.setChecked(
                !radio_anonymity.isChecked,
                true
            )
        }

        rv_goods.layoutManager = LinearLayoutManager(context)
        rv_goods.adapter = adapter
        recycler_view.layoutManager = GridLayoutManager(this, 3)
        addAddImageData()
        mAdapter = CommentAdapter(mPhotoInfos, object : CommentAdapter.DelPhotoListener {
            override fun delPhoto(path: String) {
                delItem(path)
            }

            override fun addPhoto() {
                selectImage()
            }
        })
        recycler_view.adapter = mAdapter
        edit_miaoshu.setOnTouchListener { view, event ->
            //触摸的是EditText而且当前EditText能够滚动则将事件交给EditText处理。否则将事件交由其父类处理
            if (view.getId() == R.id.edit_miaoshu && canVerticalScroll(edit_miaoshu)) {
                view.getParent().requestDisallowInterceptTouchEvent(true)
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    view.getParent().requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
        edit_miaoshu.filters = arrayOf(
            FilterUtil.getInputFilter(
                this,
                "不支持输入表情或者特殊符号", FilterUtil.MATCHER_DEFAULT
            ), InputFilter.LengthFilter(200)
        )
        getData()
    }

    private fun comment() {
        when {
            edit_miaoshu.text.toString().isNullOrEmpty() -> {
                toast("请填写评价内容")
            }
            ratingNum == 0F -> toast("请选择商品描述星级")
            serverNum == 0F -> toast("请选择服务评价星级")
            wuliuNum == 0F -> toast("请选择物流评价星级")
            else -> {
                val datas = HashMap<String, RequestBody>()
                for (i in 0 until mPhotoInfos.size) {
                    if (mPhotoInfos[i].localUrl != "发布") {
                        val cardFrontFile = File(mPhotoInfos[i].localUrl)
                        val requestFrontBody = RequestBody.create(MultipartBody.FORM, cardFrontFile)
                        datas["picture" + i + "\"; filename=\"" + cardFrontFile.name] =
                            requestFrontBody
                    }
                }
                showTipLoading("发布中")
                lifecycleScope.request({
                    APIAccount.service()
                        .commentAdd(
                            (intent.getStringExtra("uuid") ?: "").toRequestBody(),
                            (intent.getStringExtra("type") ?: "").toRequestBody(),
                            ratingNum.toInt().toString().toRequestBody(),
                            wuliuNum.toInt().toString().toRequestBody(),
                            serverNum.toInt().toString().toRequestBody(),
                            edit_miaoshu.text.toString().toRequestBody(),
                            if (radio_anonymity.isChecked) "1".toRequestBody() else "2".toRequestBody(),
                            datas
                        )
                }, object : BaseAPI<Any>() {
                    override fun onSuccess(t: Any?, state: Int, msg: String) {
                        hideTipLoading()
                        tipSuccess(msg)
                    }

                    override fun onError(e: APIException) {
                        hideTipLoading()
                        tipFail(e.eMessage)
                    }
                })
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1004) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                addPhotoNotify(when{
                    !selectList[0].compressPath.isNullOrEmpty() -> selectList[0].compressPath
                    !selectList[0].cutPath.isNullOrEmpty()->selectList[0].cutPath
                    !selectList[0].androidQToPath.isNullOrEmpty() -> selectList[0].androidQToPath
                    else-> selectList[0].path
                })
            }
        }
    }

    /**
     * 在页面显示图片
     *
     * @param path
     */
    private fun addPhotoNotify(path: String) {
        if (mPhotoInfos.size >= 1) {
            mPhotoInfos.remove(mPhotoInfos[mPhotoInfos.size - 1])
        }
        if (path.isNotEmpty()) {
            mTempPhotoInfo = PhotoInfo(path, mPhotoIndex)
            mPhotoInfos.add(mTempPhotoInfo!!)
            mPhotoIndex++
        }
        if (mPhotoInfos.size < MAX_NUM) {
            addAddImageData()
        }
        recycler_view.adapter = mAdapter
    }

    private fun getData() {
        lifecycleScope.request({
            APIAccount.service().commentGoodsShow(
                intent.getStringExtra("uuid") ?: "",
                intent.getStringExtra("type") ?: ""
            )
        }, object : BaseAPI<List<CommentGoodsShowEntity>>() {
            override fun onSuccess(t: List<CommentGoodsShowEntity>?, state: Int, msg: String) {
                adapter.setNewData(t)
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }
        })
    }

    fun selectImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)
            .loadImageEngine(GlideEngine.createGlideEngine())
            .previewImage(false)
            .isCamera(true)
            .minimumCompressSize(200)
            .compress(true)
            .isZoomAnim(true)
            .withAspectRatio(1, 1)
            .circleDimmedLayer(true)
            .showCropFrame(false)
            .showCropGrid(false)
            .isDragFrame(true)
            .rotateEnabled(true)
            .scaleEnabled(true)
            .forResult(1004)
    }

    /**
     * EditText竖直方向能否够滚动
     *
     * @param editText 须要推断的EditText
     * @return true：能够滚动   false：不能够滚动
     */
    private fun canVerticalScroll(editText: EditText): Boolean {
        //滚动的距离
        val scrollY = editText.scrollY
        //控件内容的总高度
        val scrollRange = editText.layout.height
        //控件实际显示的高度
        val scrollExtent =
            editText.height - editText.compoundPaddingTop - editText.compoundPaddingBottom
        //控件内容总高度与实际显示高度的差值
        val scrollDifference = scrollRange - scrollExtent

        return if (scrollDifference == 0) {
            false
        } else scrollY > 0 || scrollY < scrollDifference - 1

    }


    /**
     * 删除图片
     *
     * @param path
     */
    private fun delItem(path: String) {
        for (info in mPhotoInfos) {
            if (info.localUrl.equals(path)) {
                mPhotoInfos.remove(info)
                break
            }
        }
        if (!"发布".equals(mPhotoInfos[mPhotoInfos.size - 1].localUrl)) {
            addAddImageData()
        }
        mAdapter?.notifyDataSetChanged()
    }

    /**
     * 添加“+选择图片”
     */
    private fun addAddImageData() {
        val addInfo = PhotoInfo("发布", -1)
        mPhotoInfos.add(addInfo)
    }


    class Adapter :
        BaseQuickAdapter<CommentGoodsShowEntity, BaseViewHolder>(R.layout.item_comment_order) {
        override fun convert(helper: BaseViewHolder, item: CommentGoodsShowEntity?) {
            glideImage(helper.getView(R.id.miv_my_comment_fragment), item?.name ?: "")
            helper.setText(R.id.tv_my_comment_name, item?.name)
                .setText(R.id.tv_comment_money, "x${item?.num}")
        }

    }
}